package cn.hhchat.wp.service;

import cn.hhchat.wp.config.SystemProperties;
import cn.hhchat.wp.exception.EmailException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * Created this one by HMH on 2017/10/28.
 */
@Slf4j
@Service
public class EmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private SystemProperties sysConfig;

    public void sendHtml(String to, String title, String content) {
        sendMail(to,title,content,true);
    }

    public void sendText(String to, String title, String content)  {
        sendMail(to,title,content,false);
    }

    private void sendMail(String to, String title, String content, boolean isHtml)  {
        MimeMessage mailMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mailMessage);
        log.info(" ⛅ Try to send email: to: "+to+" , content: " + content);

        try {
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setFrom(sysConfig.getEmail().getUsername());
            mimeMessageHelper.setSubject(title);
            mimeMessageHelper.setText(content,isHtml);
            javaMailSender.send(mailMessage);
        } catch (MessagingException e) {
            throw new EmailException(e.getMessage());
        }
        log.info(" ⛅ Email send successfully");

    }

}
